﻿#include "fileoperation.h"
std::list<QString> SourceFilePath;//路径容器
FileOperation::FileOperation()
{
    Name="TCL警云数据管理终端";//采集站名称
       Version="V6.0.0r(WS.WM.STD)";//版本号
       Model="W2";//采集站类型
       Datetime="2024.6.11";//版本时间
       Icon="MainLogo.png";//图标
       BVersion="V6";//后台版本号
       URL="http://localhost:80/";//后台地址
       Ttime="5000";//后台心跳时间
       Btime="60000";//公告心跳时间
       MoltiDisk="D;";//多盘路径
       Mapping="true";//接口映射
       ServerAddress="127.0.0.1";//服务端IP
       ServerPor="5152";//服务端端口
       Sockettime="4000";//Socket重接时间
       UploadUrl="D:/www/sdv/Red5/" ;//上传路径
       MountUrl="C:/Station/DiskMirror/" ;//挂载根目录
       VideoEncryption="false";//视频加密
       DeleteFiles="true";//删除视频
       WhiteList="false";//白名单
       MUI="Chinese";//语言包
       MemoryLack="20";//内存不足报警
       CPULack="80";//CPU不足报警
       TheLocalKey="tcl";//账号
       TheLocalKeyPDW="1";//密码
       Area="";//地区
       Mode="标准";//上传模式
       MaxUploadRate="4000MB/s";//最大上传速率
       prior="-1";//优先口
       System="麒麟";//系统
       List="0";
       Row="0";
       PortNum="25";
       NetwordName=":";
}
//读取XMl文件配置
bool FileOperation::ReadLicenseInfo(QString ConfigName,QString key,QString &value)
{
    QApplication::processEvents();
    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());

    // Open the file
    QFile file(ConfigName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Error opening the file:" << file.errorString();
        return false;
    }

    QTextStream in(&file);
    QString xmlData = in.readAll();

    // Create a QXmlStreamReader object and set the XML data
    QXmlStreamReader xmlReader(xmlData);

    // Loop through the XML elements
    while (!xmlReader.atEnd() && !xmlReader.hasError())
    {
        // Read the next XML token
        QXmlStreamReader::TokenType token = xmlReader.readNext();

        // If the token is StartElement and the element name is "data"
        if (token == QXmlStreamReader::StartElement && xmlReader.name() == "data")
        {
            // Get the value of the "mac" attribute
            value = xmlReader.attributes().value(key).toString();
            break; // Exit the loop once we have found the "mac" attribute
        }
    }

    // Check if any error occurred while parsing
    if (xmlReader.hasError())
    {
        qDebug() << "Error parsing XML:" << xmlReader.errorString();
        file.close();
        return false;
    }

    // Close the file
    file.close();
    return true;

}
bool FileOperation::ReadInfo(QString ConfigName,QString &value)
{
    //QApplication::processEvents();
    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());
    // 打开文件
    QFile file(ConfigName);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        // 创建文本流
        QTextStream in(&file);

        // 读取第一行
        value = in.readLine();

        // 输出第一行内容
        qDebug() << "第一行内容：" << value;

        // 关闭文件
        file.close();
        return true;
    }
    else
    {
        qDebug() << "无法打开文件：" << ConfigName;
    }
    return false;
}
//读取XMl文件配置
bool FileOperation::ReadInfo(QString ConfigName)
{
    if(ConfigName=="config.ini")
    {
        //将当前工作目录设置为应用程序所在的目录
        QDir::setCurrent(QCoreApplication::applicationDirPath());
        // 打开配置文件
        QFile file(ConfigName);
        if (!file.open(QIODevice::ReadOnly  | QIODevice::Text))
        {
            qDebug() << "Failed to open file.";
            return false;
        }
        QSet<QString> expectedKeys = {
            "BVersion", "URL", "Ttime", "Btime", "MoltiDisk", "Mapping",
            "ServerAddress", "ServerPor", "Sockettime", "UploadUrl",
            "MountUrl", "VideoEncryption", "DeleteFiles" ,"WhiteList",
            "MUI","MemoryLack","CPULack","TheLocalKey" ,"prior" ,
            "TheLocalKeyPDW","Area","MaxUploadRate","Mode" ,"System","Row","List","PortNum","NetwordName"

        };
        // 创建 QXmlStreamReader 对象
        QXmlStreamReader reader(&file);

        // 遍历配置文件
        while (!reader.atEnd())
        {
            // 读取下一个 XML 标签
            reader.readNext();

            // 如果是开始标签，且标签名为 add
            if (reader.isStartElement() && reader.name() == "add")
            {
                // 获取 key 属性的值
                QString key = reader.attributes().value("key").toString();
                QString value= reader.attributes().value("value").toString();

                // 根据 key 更新相应的变量
                if (key == "BVersion") {
                    BVersion = value;
                } else if (key == "URL") {
                    URL = value;
                }else if (key == "Ttime") {
                    Ttime = value;
                }else if (key == "Btime") {
                    Btime = value;
                }else if (key == "MoltiDisk") {
                    MoltiDisk = value;
                }else if (key == "Mapping") {
                    Mapping = value;
                }else if (key == "ServerAddress") {
                    ServerAddress = value;
                }else if (key == "ServerPor") {
                    ServerPor = value;
                }else if (key == "Sockettime") {
                    Sockettime = value;
                }else if (key == "UploadUrl") {
                    UploadUrl = value;
                }else if (key == "MountUrl") {
                    MountUrl = value;
                }else if (key == "VideoEncryption") {
                    VideoEncryption = value;
                }else if (key == "DeleteFiles") {
                    DeleteFiles = value;
                }else if (key == "WhiteList") {
                    WhiteList = value;
                }else if (key == "MUI") {
                    MUI = value;
                }else if (key == "MemoryLack") {
                    MemoryLack = value;
                }else if (key == "CPULack") {
                    CPULack = value;
                }else if (key == "TheLocalKey") {
                    TheLocalKey = value;
                }else if (key == "TheLocalKeyPDW") {
                    TheLocalKeyPDW = value;
                }else if (key == "Area") {
                    Area = value;
                }else if (key == "MaxUploadRate") {
                    MaxUploadRate = value;
                }else if (key == "Mode") {
                    Mode = value;
                }else if (key == "System") {
                    System = value;
                }else if (key == "Row") {
                    Row = value;
                }else if (key == "List") {
                    List = value;
                }else if (key == "prior") {
                    prior = value;
                }else if (key == "PortNum") {
                    PortNum = value;
                }else if (key == "NetwordName") {
                    NetwordName = value;
                }else
                {
                    qDebug() << "XML error:";
                }
                // 从预期的键集合中移除已找到的键
                expectedKeys.remove(key);

            }

        }
        // 检查是否所有预期的键都已被找到
        if (expectedKeys.isEmpty()) {
            qDebug() << "All expected keys were found.";
            // 关闭配置文件
            file.close();
            return true;
            // 所有值都存在，可以继续处理
        }

        // 关闭配置文件
        file.close();
        return false;
    }
    else if (ConfigName=="config_label.ini")
    {
        //将当前工作目录设置为应用程序所在的目录
        QDir::setCurrent(QCoreApplication::applicationDirPath());
        // 打开配置文件
        QFile file(ConfigName);
        if (!file.open(QIODevice::ReadOnly  | QIODevice::Text))
        {
            qDebug() << "Failed to open file.";
            return false;
        }
        QSet<QString> expectedKeys = {
            "Model", "Name", "Icon", "Version", "Datetime"
        };
        // 创建 QXmlStreamReader 对象
        QXmlStreamReader reader(&file);

        // 遍历配置文件
        while (!reader.atEnd())
        {
            // 读取下一个 XML 标签
            reader.readNext();

            // 如果是开始标签，且标签名为 add
            if (reader.isStartElement() && reader.name() == "add")
            {
                // 获取 key 属性的值
                QString key = reader.attributes().value("key").toString();
                QString value= reader.attributes().value("value").toString();

                // 根据 key 更新相应的变量
                if (key == "Model") {
                    Model = value;
                } else if (key == "Icon") {
                    Icon = value;
                }else if (key == "Name") {
                    Name = value;
                }else if (key == "Version") {
                    Version = value;
                }else if (key == "Datetime") {
                    Datetime = value;
                }else
                {
                    qDebug() << "XML error:";
                }
                // 从预期的键集合中移除已找到的键
                expectedKeys.remove(key);

            }

        }
        // 检查是否所有预期的键都已被找到
        if (expectedKeys.isEmpty()) {
            qDebug() << "All expected keys were found.";
            // 关闭配置文件
            file.close();
            return true;
            // 所有值都存在，可以继续处理
        }

        // 关闭配置文件
        file.close();
        return false;
    }
}

//根据key读取路径配置文件
bool FileOperation::ReadRouteInfo(QString ConfigName,QString key,QString &value)
{
    QApplication::processEvents();
    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());
    // 打开配置文件
    QFile file(ConfigName);
    try {
        if (!file.open(QIODevice::ReadOnly  | QIODevice::Text))
        {
            qDebug() << "Failed to open file.";
            return false;
        }
        QTextStream reader(&file);
        // 遍历配置文件
        while (!reader.atEnd())
        {
            QString str =reader.readLine();
            QStringList parts = str.split('=');

            if (parts.size() >= 2) {
                QString key1 = parts[0];
                QString value1 = parts[1];
                if(key==key1&&value1!="")
                {
                    value=value1;
                    qDebug() << "Key: " << key1;
                    qDebug() << "Value: " << value1;
                    // 关闭配置文件
                    file.close();
                    return true;
                }
            }

        }
        // 关闭配置文件
        file.close();
        return false;
    } catch (const std::exception& e) {
        // Handle the exception, log the error, or perform necessary cleanup.
        qDebug() << "Exception caught while processing the file: " << e.what();
        file.close(); // Ensure the file is closed even in case of an exception.
        return false;
    }
}
//根据value读取路径文件
bool FileOperation::ReadRouteValueInfo(QString ConfigName,QString &key,QString value)
{
    QApplication::processEvents();
    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());
    // 打开配置文件
    QFile file(ConfigName);
    if (!file.open(QIODevice::ReadOnly  | QIODevice::Text))
    {
        qDebug() << "ReadRouteValueInfo Failed to open file."<<ConfigName;
        // qDebug() << "ReadRouteValueInfo Failed to open file.";
        return false;
    }
    QTextStream reader(&file);
    // 遍历配置文件
    while (!reader.atEnd())
    {
        QString str =reader.readLine();
        QStringList parts = str.split('=');

        if (parts.size() >= 2) {
            QString key1 = parts[0];
            QString value1 = parts[1];
            if(value1==value)
            {
                key=key1;
                // 关闭配置文件
                file.close();
                return true;
            }
        }
    }
    // 关闭配置文件
    file.close();
    return false;
}


//按键值写入日记文件
bool FileOperation::WriteInfo(QString key,QString value)
{
    QApplication::processEvents();
    // 获取当前时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString currentDateTimeString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString currentDate = currentDateTime.toString("yyyy-MM-dd");
    QString currentHour = currentDateTime.toString("hh.00");

    // 设置日志文件名
    QString logFileName = currentDateTime.toString("yyyy-MM-dd_hh.00") + ".log";

    // 创建日志文件夹
    QString logFolderPath = QDir::currentPath() + "/log";
    if (!QDir(logFolderPath).exists()) {
        QDir().mkdir(logFolderPath);
    }

    // 创建日期文件夹
    QString dateFolderPath = logFolderPath + "/" + currentDate;
    if (!QDir(dateFolderPath).exists()) {
        QDir().mkdir(dateFolderPath);
    }

    //    // 创建小时文件夹
    //    QString hourFolderPath = dateFolderPath + "/" + currentHour;
    //    if (!QDir(hourFolderPath).exists()) {
    //        QDir().mkdir(hourFolderPath);
    //    }

    // 创建日志文件
    QString logFilePath = dateFolderPath + "/" + logFileName;
    // 打开日志文件
    QFile file(logFilePath);

    if (file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        // 创建一个 QTextStream 对象，用于写入日志信息
        QTextStream out(&file);


        // 输出日志信息到控制台

        // 输出日志信息到日志文件
        out <<currentDateTimeString<<key << "=" <<value<< endl;
        qDebug()<<currentDateTimeString<<QString("服务:")<<key << "=" <<value<< endl;

        // 关闭日志文件
        file.close();
        return true;
    }
    return false;
}
//打印写入日记文件
bool FileOperation::WriteInfo(QString key)
{
    QApplication::processEvents();
    // 获取当前时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString currentDateTimeString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString currentDate = currentDateTime.toString("yyyy-MM-dd");
    QString currentHour = currentDateTime.toString("hh.00");

    // 设置日志文件名
    QString logFileName = currentDateTime.toString("yyyy-MM-dd_hh.00") + ".log";

    // 创建日志文件夹
    QString logFolderPath = QDir::currentPath() + "/log";
    if (!QDir(logFolderPath).exists()) {
        QDir().mkdir(logFolderPath);
    }

    // 创建日期文件夹
    QString dateFolderPath = logFolderPath + "/" + currentDate;
    if (!QDir(dateFolderPath).exists()) {
        QDir().mkdir(dateFolderPath);
    }

    // 创建日志文件
    QString logFilePath = dateFolderPath + "/" + logFileName;
    // 打开日志文件
    QFile file(logFilePath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        // 创建一个 QTextStream 对象，用于写入日志信息
        QTextStream out(&file);




        // 输出日志信息到日志文件
        out <<currentDateTimeString<<QString("服务:")<<key << endl;
        qDebug()<<currentDateTimeString<<QString("服务:")<<key << endl;

        // 关闭日志文件
        file.close();
        return true;
    }
    return false;
}


//写入保存文件
bool FileOperation::WriteSaveInfo(QString ConfigName,QString key,QString value)
{
    QApplication::processEvents();
    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());
    // 打开配置文件
    QFile file(ConfigName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
    {
        qDebug() << "WriteSaveInfo 3 Failed to open file.";
        return false;
    }
    else
    {
        QTextStream out(&file);
        QString str= QString("%1=%2").arg(key).arg(value);
        out << str<<endl;
        // 关闭日志文件
        file.close();
        return true;
    }
}
//清空保存文件
bool FileOperation::DeleteSaveInfo(QString ConfigName)
{
    QApplication::processEvents();
    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());
    // 打开配置文件
    QFile file(ConfigName);
    if (!file.open(QIODevice::ReadWrite   | QIODevice::Text))
    {
        qDebug() << "Failed to open file.";
        return false;
    }
    else
    {
        // 清空文件内容
        file.resize(0);
        // 关闭日志文件
        file.close();
        return true;
    }
}
bool FileOperation::UpdateXmlKeyValue(const QString &filePath, const QString &key, const QString &newValue) {

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件以进行读取:" << file.errorString();
        return false;
    }

    QDomDocument doc;
    if (!doc.setContent(&file)) {
        qDebug() << "无法解析XML文件";
        file.close();
        return false;
    }

    file.close();

    // 查找所有<add>元素
    QDomNodeList nodeList = doc.elementsByTagName("add");
    for (int i = 0; i < nodeList.size(); ++i) {
        QDomElement element = nodeList.at(i).toElement();

        // 检查键是否匹配
        if (element.attribute("key") == key) {
            // 更新值
            element.setAttribute("value", newValue);
            break; // 假设每个键只出现一次，找到后退出循环
        }
    }

    // 将修改后的XML写回文件
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件以进行写入:" << file.errorString();
        return false;
    }

    QTextStream out(&file);
    doc.save(out, 4); // 第二个参数是缩进量
    file.close();

    return true;
}

//根据key值修改路径文件
bool FileOperation::UpdateRouteValueInfo(QString ConfigName,QString key,QString value)
{
    QApplication::processEvents();
    bool isEmptyFile=true;
    QFile file(ConfigName);
    if (file.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        // 读取文件内容
        QTextStream stream(&file);
        QString content = stream.readAll();

        // 判断文件内容是否为空
        if(content=="")
        {
            isEmptyFile=false;
        }

        // 解析每一行的键值对
        QStringList lines = content.split("\n");
        QStringList newLines;
        bool keyFound = false; // 标记是否找到要修改的键
        for (QString line : lines)
        {
            line = line.trimmed();
            if (line.startsWith(QString("%1=").arg(key)))
            {
                // 修改要修改的键对应的值
                line = QString("%1=%2").arg(key, value);
                keyFound = true; // 找到了要修改的键
            }
            // 将处理后的行加入新的列表
            newLines.append(line);
        }
        if(!keyFound)
        {
            // 添加新的键值对行
            QString newLine = QString("%1=%2").arg(key, value);
            newLines.append(newLine);
        }
        // 如果没有找到要修改的键，并且文件不为空，则将新的键值对添加到配置文件末尾
        if (!keyFound && !isEmptyFile)
        {
            // 将新的键值对列表拼接成字符串
            content = newLines.join("");
        }
        else
        {
            // 将新的键值对列表拼接成字符串
            content = newLines.join("\n");
        }
        // 清空文件内容
        file.resize(0);

        // 将修改后的内容写回文件
        stream << content;

        // 关闭文件
        file.close();
        return true;
    }
    else
    {
        return false;
    }
    return false;
}
int FileOperation::copyFiles(const QString& sourceDirPath, const QString& destinationDirPath,const QString& serialnumber,const QString& timestr,const QString& Badgenum,const QString Device,bool DeleteFiles,int &num,int MaxSpeed,int serialportnum)
{
    qDebug() << "copyFiles8:" << destinationDirPath;
    qDebug() << "copyFiles8:" << sourceDirPath;
    //QApplication::processEvents();

    QDir sourceDir(sourceDirPath);
    QString logFolderPath =  destinationDirPath+ "/"  + Badgenum;
    if (!QDir(logFolderPath).exists()) {
        QDir().mkdir(logFolderPath);
    }


    QString dateFolderPath = logFolderPath + QString("/%1_%2").arg(serialnumber).arg(timestr);
    if (!QDir(dateFolderPath).exists()) {
        QDir().mkdir(dateFolderPath);
    }

    QString video = dateFolderPath + "/video";
    if (!QDir(video).exists()) {
        QDir().mkdir(video);
    }
    QString photo = dateFolderPath + "/photo";
    if (!QDir(photo).exists()) {
        QDir().mkdir(photo);
    }
    QString log = dateFolderPath + "/log";
    if (!QDir(log).exists()) {
        QDir().mkdir(log);
    }
    QString audio = dateFolderPath + "/audio";
    if (!QDir(audio).exists()) {
        QDir().mkdir(audio);
    }
    // 获取源目录中的所有文件和文件夹
    QStringList fileList = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

    // 遍历文件列表
    foreach (QString file, fileList) {
        QString sourceFilePath = sourceDir.filePath(file);
        QString destinationFilePath ;//= destinationDir.filePath(file);
        qDebug() << "destinationDirPath:" << destinationDirPath;
        qDebug() << "sourceFilePath:" << sourceFilePath;
        if (QFileInfo(sourceFilePath).isDir()) {
            if (! QDir().mkpath(destinationDirPath)) {
                qDebug() << "Failed to create directory:" << destinationDirPath;
                continue;
            }
            copyFiles(sourceFilePath, destinationDirPath,serialnumber,timestr,Badgenum,Device,DeleteFiles,num,MaxSpeed,serialportnum);
        } else {
            if(!IsUpload[serialportnum])
            {
                WriteInfo("取消上传");
                return num;
            }

            // 如果是文件且是MP4或JPG格式，则拷贝到目标目录的相应子目录下
            QFileInfo fileInfo(sourceFilePath);
            QString fileExtension = fileInfo.suffix().toLower();

            if (fileExtension == "mp4"||fileExtension == "mov"||fileExtension == "mpg"||fileExtension == "avi"||fileExtension == "mts"||fileExtension == "flv"||fileExtension == "3gp"||fileExtension == "mkv") {
                QDir destinationDir(video);
                destinationFilePath = destinationDir.filePath(file);
                qDebug() << "video" << destinationFilePath;
            } else if (fileExtension == "jpg"||fileExtension == "jpeg"||fileExtension == "png"||fileExtension == "bmp") {
                QDir destinationDir(photo);
                destinationFilePath = destinationDir.filePath(file);
                qDebug() << "jpg" << destinationFilePath;
            } else if (fileExtension == "txt"||fileExtension == "log") {
                QDir destinationDir(log);
                destinationFilePath = destinationDir.filePath(file);
                qDebug() << "txt" << destinationFilePath;
            } else if (fileExtension == "wav"||fileExtension == "aac"||fileExtension == "mp3"||fileExtension == "3gpp") {
                QDir destinationDir(audio);
                destinationFilePath = destinationDir.filePath(file);
                qDebug() << "wav" << destinationFilePath;
            } else {
                // 如果是其他文件类型，则不进行拷贝
                continue;
            }

            QDateTime lastModified = fileInfo.lastModified();

            // 检查是否成功获取到文件时间
            if (lastModified.isValid()) {
                // 使用获取到的文件时间
                // ...
            } else {
                // 获取当前时间作为替代
                lastModified = QDateTime::currentDateTime();
                // ...
            }
            if(fileExtension == "mp4"||fileExtension=="jpg"||fileExtension=="wav")
            {
                QString fileName=fileInfo.baseName();
                QStringList fileInfoParts=fileName.split("_");
                if(!fileInfoParts.isEmpty())
                {
                    QString possibleDate=fileInfoParts.first();
                    possibleDate =extractTimestamp(possibleDate);
                    WriteInfo(QString("Copied file: possibleDate%1").arg(possibleDate));
                    if(possibleDate!="")
                    {
                        QString format = "yyyyMMddHHmmss";
                        lastModified = QDateTime::fromString(possibleDate, format);
                    }
                }

            }


            double fileSize = fileInfo.size()/(1024*1024);  // 获取文件大小，以字节为单位
            qDebug() << "Copied file: 文件名字为" << fileInfo.fileName();
            qDebug() << "Copied file: 文件大小为" << fileSize;
            qDebug() << "Copied file: 修改时间为" << lastModified.toString("yyyyMMddhhmmss");
            qDebug() << "Copied file:" << sourceFilePath;

            WriteInfo(QString("Copied file: 文件名字为%1").arg(fileInfo.fileName()));
            WriteInfo(QString("Copied file: 文件大小为%1").arg( fileSize));
            WriteInfo(QString("Copied file: 修改时间为%1").arg( lastModified.toString("yyyyMMddhhmmss")));

            // 获取当前时间
            QDateTime currentDateTime = QDateTime::currentDateTime();
            QString currentDateTimeString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss.zzz");
            QString case_number =validateFileName(fileInfo.fileName());
            if (!QFile::copy(sourceFilePath, destinationFilePath)) {
                qDebug() << "Failed to copy file:" << sourceFilePath;
                qDebug() << "Error details:" << QFile(destinationFilePath).errorString();
                continue;
            }

            // }
            if(DeleteFiles)
            {
                if (!QFile::remove(sourceFilePath)) {
                    qDebug() << "Failed to remove file:" << destinationFilePath;
                    continue;
                }
            }


            // 输出结果
            if (!case_number.isEmpty()) {
                while (true) {
                    if(WriteSaveInfo(serialnumber, fileInfo.fileName(), timestr, lastModified.toString("yyyyMMddhhmmss"), "",case_number,destinationDirPath)/*&&                                                                                    WriteSaveInfo(QString("%1:/copy_log.log").arg(Device),currentDateTimeString,fileInfo.fileName())*/)//记录索引和记录日记
                    {
                        WriteInfo(QString("记录成功:%1").arg(sourceFilePath));

                        //SourceFilePath.push_back(sourceFilePath);

                        break;
                        num++;
                    }
                }
            }
            else
            {
                while (true) {


                    if(WriteSaveInfo(serialnumber, fileInfo.fileName(), timestr, lastModified.toString("yyyyMMddhhmmss"), "",destinationDirPath)/*&&
                                                                                                                                                          WriteSaveInfo(QString("%1:/copy_log.log").arg(Device),currentDateTimeString,fileInfo.fileName())*/)//记录索引和记录日记
                    {
                        WriteInfo(QString("记录成功:%1").arg(sourceFilePath));

                        //SourceFilePath.push_back(sourceFilePath);


                        num++;
                        break;
                    }
                }
            }

        }
    }
    return num;
}


int FileOperation::copyFiles(const QString& sourceDirPath, const QString& destinationDirPath,const QString& serialnumber,const QString& timestr,const QString& Badgenum,const QString Device,bool DeleteFiles,QString case_number,QString trafficCaseTable,QString file_type_id,int &num,int MaxSpeed)
{
    qDebug() << "copyFiles9:" << destinationDirPath;
    qDebug() << "copyFiles9:" << sourceDirPath;
    //QApplication::processEvents();
    // SourceFilePath.clear();

    QDir sourceDir(sourceDirPath);
    QString logFolderPath =  destinationDirPath + Badgenum;
    if (!QDir(logFolderPath).exists()) {
        QDir().mkdir(logFolderPath);
    }


    QString dateFolderPath = logFolderPath + QString("/%1_%2").arg(serialnumber).arg(timestr);
    if (!QDir(dateFolderPath).exists()) {
        QDir().mkdir(dateFolderPath);
    }

    QString video = dateFolderPath + "/video";
    if (!QDir(video).exists()) {
        QDir().mkdir(video);
    }
    QString photo = dateFolderPath + "/photo";
    if (!QDir(photo).exists()) {
        QDir().mkdir(photo);
    }
    QString log = dateFolderPath + "/log";
    if (!QDir(log).exists()) {
        QDir().mkdir(log);
    }
    QString audio = dateFolderPath + "/audio";
    qDebug() << audio;
    if (!QDir(audio).exists()) {
        QDir().mkdir(audio);

    }
    QString sourceFilePath = sourceDir.filePath(sourceDirPath);
    QString destinationFilePath ;//= destinationDir.filePath(file);
    qDebug() << "sourceFilePath:" << sourceFilePath;

    if (QFileInfo(sourceFilePath).isDir()) {
        if (! QDir().mkpath(destinationDirPath)) {
            qDebug() << "Failed to create directory:" << destinationDirPath;
        }
    } else {
        // 如果是文件且是MP4或JPG格式，则拷贝到目标目录的相应子目录下
        QFileInfo fileInfo(sourceFilePath);
        QString fileExtension = fileInfo.suffix().toLower();
        int lastSlashIndex=sourceFilePath.lastIndexOf('/');
        QString filename=sourceFilePath.mid(lastSlashIndex);


        if (fileExtension == "mp4"||fileExtension == "mov"||fileExtension == "mpg"||fileExtension == "avi"||fileExtension == "mts"||fileExtension == "flv"||fileExtension == "3gp"||fileExtension == "mkv") {
            destinationFilePath = video+"/"+filename;
            qDebug() << "video" << destinationFilePath;
        } else if (fileExtension == "jpg"||fileExtension == "jpeg"||fileExtension == "png"||fileExtension == "bmp") {
            QDir destinationDir(photo);
            destinationFilePath = photo+"/"+filename;
            qDebug() << "jpg" << destinationFilePath;
        } else if (fileExtension == "txt"||fileExtension == "log") {
            QDir destinationDir(log);
            destinationFilePath = log+"/"+filename;
            qDebug() << "txt" << destinationFilePath;
        } else if (fileExtension == "wav"||fileExtension == "aac"||fileExtension == "mp3"||fileExtension == "3gpp") {
            QDir destinationDir(audio);
            destinationFilePath = audio+"/"+filename;
            qDebug() << "destinationDir"<<destinationDir;
            qDebug() << "wav" << destinationFilePath;
        } else {
            // 如果是其他文件类型，则不进行拷贝

        }
        QString time ="";
        QDateTime lastModified = fileInfo.created();
        // 检查是否成功获取到文件时间
        if (lastModified.isValid()) {
            // 使用获取到的文件时间
            // ...
        } else {
            // 获取当前时间作为替代
            lastModified = QDateTime::currentDateTime();
            // ...
        }
        double fileSize = fileInfo.size()/1024/1024;  // 获取文件大小，以字节为单位
        qDebug() << "Copied file: 文件名字为" << fileInfo.fileName();
        qDebug() << "Copied file: 文件大小为" << fileSize;
        qDebug() << "Copied file: 修改时间为" << lastModified.toString("yyyyMMddhhmmss");
        qDebug() << "Copied file:" << sourceFilePath;

        WriteInfo(QString("Copied file: 文件名字为%1").arg(fileInfo.fileName()));
        WriteInfo(QString("Copied file: 文件大小为%1").arg( fileSize));
        WriteInfo(QString("Copied file: 修改时间为%1").arg( lastModified.toString("yyyyMMddhhmmss")));


        // 获取当前时间
        QDateTime currentDateTime = QDateTime::currentDateTime();
        QString currentDateTimeString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss.zzz");
        if (!QFile::copy(sourceFilePath, destinationFilePath)) {
            qDebug() << "Failed to copy file:" << sourceFilePath;
            qDebug() << "Error details:" << QFile(destinationFilePath).errorString();
            return num ;
        }

        // }

        if(WriteSaveInfo(serialnumber, fileInfo.fileName(), timestr, lastModified.toString("yyyyMMddhhmmss"), "",case_number, trafficCaseTable, file_type_id,destinationDirPath)/*&&
                                                                                                WriteSaveInfo(QString("%1:/copy_log.log").arg(Device),currentDateTimeString,fileInfo.fileName())*/)//记录索引和记录日记
        {
            WriteInfo(QString("记录成功:%1").arg(sourceFilePath));
            qDebug() << "记录成功:" << sourceFilePath;
            //SourceFilePath.push_back(sourceFilePath);
            num++;
        }

        // }
    }

    return num;

}
//int FileOperation::copyFiles(const QString& sourceDirPath, const QString& destinationDirPath,const QString& serialnumber,const QString& timestr,const QString& Badgenum,const QString Device,bool DeleteFiles,double& totalSize)
//{
//     qDebug() << "copyFiles8:" << destinationDirPath;
//     qDebug() << "copyFiles8:" << sourceDirPath;
//    QApplication::processEvents();

//    int num=0;
//    QDir sourceDir(sourceDirPath);
//    QString logFolderPath =  destinationDirPath+ "/"  + Badgenum;
//    if (!QDir(logFolderPath).exists()) {
//        QDir().mkdir(logFolderPath);
//    }


//    QString dateFolderPath = logFolderPath + QString("/%1_%2").arg(serialnumber).arg(timestr);
//    if (!QDir(dateFolderPath).exists()) {
//        QDir().mkdir(dateFolderPath);
//    }

//    QString video = dateFolderPath + "/video";
//    if (!QDir(video).exists()) {
//        QDir().mkdir(video);
//    }
//    QString photo = dateFolderPath + "/photo";
//    if (!QDir(photo).exists()) {
//        QDir().mkdir(photo);
//    }
//    QString log = dateFolderPath + "/log";
//    if (!QDir(log).exists()) {
//        QDir().mkdir(log);
//    }
//    QString audio = dateFolderPath + "/audio";
//    if (!QDir(audio).exists()) {
//        QDir().mkdir(audio);
//    }

//    // 获取源目录中的所有文件和文件夹
//    QStringList fileList = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

//    // 遍历文件列表
//    foreach (QString file, fileList) {
//        QString sourceFilePath = sourceDir.filePath(file);
//        QString destinationFilePath ;//= destinationDir.filePath(file);
// qDebug() << "destinationDirPath:" << destinationDirPath;
// qDebug() << "sourceFilePath:" << sourceFilePath;
//        if (QFileInfo(sourceFilePath).isDir()) {
//            if (! QDir().mkpath(destinationDirPath)) {
//                qDebug() << "Failed to create directory:" << destinationDirPath;
//                continue;
//            }
//            copyFiles(sourceFilePath, destinationDirPath,serialnumber,timestr,Badgenum,Device,DeleteFiles,totalSize);
//        } else {
//            // 如果是文件且是MP4或JPG格式，则拷贝到目标目录的相应子目录下
//            QFileInfo fileInfo(sourceFilePath);
//            QString fileExtension = fileInfo.suffix().toLower();

//            if (fileExtension == "mp4") {
//                QDir destinationDir(video);
//                destinationFilePath = destinationDir.filePath(file);
//                qDebug() << "video" << destinationFilePath;
//            } else if (fileExtension == "jpg") {
//                QDir destinationDir(photo);
//                destinationFilePath = destinationDir.filePath(file);
//                qDebug() << "jpg" << destinationFilePath;
//            } else if (fileExtension == "txt") {
//                QDir destinationDir(log);
//                destinationFilePath = destinationDir.filePath(file);
//                qDebug() << "txt" << destinationFilePath;
//            } else if (fileExtension == "wav") {
//                QDir destinationDir(audio);
//                destinationFilePath = destinationDir.filePath(file);
//                qDebug() << "wav" << destinationFilePath;
//            } else {
//                // 如果是其他文件类型，则不进行拷贝
//                continue;
//            }
//            QString time ="";
////            if(!ReadRouteValueInfo(QString("%1copy_log.log").arg(Device),time,sourceFilePath))//判断是否已经拷贝
////            {
//                if (!QFile::copy(sourceFilePath, destinationFilePath)) {
//                    qDebug() << "Failed to copy file:" << sourceFilePath;
//                    qDebug() << "Error details:" << QFile(destinationFilePath).errorString();
//                    continue;
//                }

//                QDateTime lastModified = fileInfo.lastModified();
//                double fileSize = fileInfo.size()/(1024*1024);  // 获取文件大小，以字节为单位
//                qDebug() << "Copied file: 文件名字为" << fileInfo.fileName();
//                qDebug() << "Copied file: 文件大小为" << fileSize;
//                qDebug() << "Copied file: 修改时间为" << lastModified.toString("yyyyMMddhhmmss");
//                qDebug() << "Copied file:" << sourceFilePath;

//                WriteInfo(QString("Copied file: 文件名字为%1").arg(fileInfo.fileName()));
//                WriteInfo(QString("Copied file: 文件大小为%1").arg( fileSize));
//                WriteInfo(QString("Copied file: 修改时间为%1").arg( lastModified.toString("yyyyMMddhhmmss")));
//                totalSize+=fileSize;
//                // 获取当前时间
//                QDateTime currentDateTime = QDateTime::currentDateTime();
//                QString currentDateTimeString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss.zzz");
//                if(WriteSaveInfo(serialnumber, fileInfo.fileName(), timestr, lastModified.toString("yyyyMMddhhmmss"), "",destinationDirPath))//记录索引和记录日记
//                {
//                    qDebug() << "记录成功:" << sourceFilePath;
//                    SourceFilePath.push_back(sourceFilePath);
//                    num++;
//                }

//            //}
//        }
//    }
//    return num;
//}
//int FileOperation::copyFiles(const QString& sourceDirPath, const QString& destinationDirPath,const QString& serialnumber,const QString& timestr,const QString& Badgenum,const QString Device,bool DeleteFiles,double& totalSize,QString case_number,QString trafficCaseTable,QString file_type_id)
//{
//         qDebug() << "copyFiles9:" << destinationDirPath;
//                  qDebug() << "copyFiles9:" << sourceDirPath;
//    QApplication::processEvents();
//    // SourceFilePath.clear();
//    int num=0;
//    QDir sourceDir(sourceDirPath);
//    QString logFolderPath =  destinationDirPath + Badgenum;
//    if (!QDir(logFolderPath).exists()) {
//        QDir().mkdir(logFolderPath);
//    }


//    QString dateFolderPath = logFolderPath + QString("/%1_%2").arg(serialnumber).arg(timestr);
//    if (!QDir(dateFolderPath).exists()) {
//        QDir().mkdir(dateFolderPath);
//    }

//    QString video = dateFolderPath + "/video";
//    if (!QDir(video).exists()) {
//        QDir().mkdir(video);
//    }
//    QString photo = dateFolderPath + "/photo";
//    if (!QDir(photo).exists()) {
//        QDir().mkdir(photo);
//    }
//    QString log = dateFolderPath + "/log";
//    if (!QDir(log).exists()) {
//        QDir().mkdir(log);
//    }
//    QString audio = dateFolderPath + "/audio";
//    qDebug() << audio;
//    if (!QDir(audio).exists()) {
//        QDir().mkdir(audio);

//    }
//        QString sourceFilePath = sourceDir.filePath(sourceDirPath);
//        QString destinationFilePath ;//= destinationDir.filePath(file);
//        qDebug() << "sourceFilePath:" << sourceFilePath;

//        if (QFileInfo(sourceFilePath).isDir()) {
//            if (! QDir().mkpath(destinationDirPath)) {
//                qDebug() << "Failed to create directory:" << destinationDirPath;
//            }
//           // copyFiles(sourceFilePath, destinationDirPath,serialnumber,timestr,Badgenum,Device,DeleteFiles,totalSize);
//        } else {
//            // 如果是文件且是MP4或JPG格式，则拷贝到目标目录的相应子目录下
//            QFileInfo fileInfo(sourceFilePath);
//            QString fileExtension = fileInfo.suffix().toLower();
//int lastSlashIndex=sourceFilePath.lastIndexOf('/');
//QString filename=sourceFilePath.mid(lastSlashIndex);
//            if (fileExtension == "mp4") {
//                destinationFilePath = video+"/"+filename;
//                qDebug() << "video" << destinationFilePath;
//            } else if (fileExtension == "jpg") {
//                QDir destinationDir(photo);
//                 destinationFilePath = photo+"/"+filename;
//                qDebug() << "jpg" << destinationFilePath;
//            } else if (fileExtension == "txt") {
//                QDir destinationDir(log);
//                destinationFilePath = log+"/"+filename;
//                qDebug() << "txt" << destinationFilePath;
//            } else if (fileExtension == "wav") {
//                QDir destinationDir(audio);
//                destinationFilePath = audio+"/"+filename;
//                    qDebug() << "destinationDir"<<destinationDir;
//                qDebug() << "wav" << destinationFilePath;
//            }
//            QString time ="";
////            if(!ReadRouteValueInfo(QString("%1copy_log.log").arg(Device),time,sourceFilePath))//判断是否已经拷贝
////            {

//                if (!QFile::copy(sourceFilePath, destinationFilePath)) {
//                    qDebug() << "Failed to copy file:" << sourceFilePath;
//                    qDebug() << "Error details:" << QFile(destinationFilePath).errorString();
//                    //continue;
//                }
//                QDateTime lastModified = fileInfo.lastModified();
//                double fileSize = fileInfo.size()/1024/1024;  // 获取文件大小，以字节为单位
//                qDebug() << "Copied file: 文件名字为" << fileInfo.fileName();
//                qDebug() << "Copied file: 文件大小为" << fileSize;
//                qDebug() << "Copied file: 修改时间为" << lastModified.toString("yyyyMMddhhmmss");
//                qDebug() << "Copied file:" << sourceFilePath;

//                WriteInfo(QString("Copied file: 文件名字为%1").arg(fileInfo.fileName()));
//                WriteInfo(QString("Copied file: 文件大小为%1").arg( fileSize));
//                WriteInfo(QString("Copied file: 修改时间为%1").arg( lastModified.toString("yyyyMMddhhmmss")));
//                totalSize+=fileSize;

//                // 获取当前时间
//                QDateTime currentDateTime = QDateTime::currentDateTime();
//                QString currentDateTimeString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss.zzz");
//                if(WriteSaveInfo(serialnumber, fileInfo.fileName(), timestr, lastModified.toString("yyyyMMddhhmmss"), "",case_number, trafficCaseTable, file_type_id,destinationDirPath))//记录索引和记录日记
//                {
//                    qDebug() << "记录成功:" << sourceFilePath;
//                    //SourceFilePath.push_back(sourceFilePath);
//                    num++;
//                }

//          //  }
//        }

//    return num;

//}
//bool ReadConfig::copyFiles(const QString& sourceDirPath, const QString& destinationDirPath,const QString& serialnumber,const QString& timestr)
//{
//    QDir sourceDir(sourceDirPath);
//    QDir destinationDir(destinationDirPath);

//    // 获取源目录中的所有文件和文件夹
//    QStringList fileList = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

//    // 遍历文件列表
//    foreach (QString file, fileList) {
//        QString sourceFilePath = sourceDir.filePath(file);
//        QString destinationFilePath = destinationDir.filePath(file);

//        if (QFileInfo(sourceFilePath).isDir()) {
//            // 如果是文件夹，则递归地拷贝
//            if (!destinationDir.mkpath(file)) {
//                qDebug() << "Failed to create directory:" << destinationFilePath;
//                continue;
//            }
//            copyFiles(sourceFilePath, destinationFilePath,serialnumber,timestr);
//        } else {
//            // 如果是文件且是MP4或JPG格式，则拷贝到目标目录
//            QFileInfo fileInfo(sourceFilePath);
//            QString fileExtension = fileInfo.suffix().toLower();
//            if (fileExtension == "mp4" || fileExtension == "jpg") {
//                qDebug() << "destinationFilePath:" << destinationFilePath;
//                if (!QFile::copy(sourceFilePath, destinationFilePath)) {
//                    qDebug() << "Failed to copy file:" << sourceFilePath;
//                    continue;
//                }
//                QDateTime lastModified = fileInfo.lastModified();
//                qDebug() << "Copied file:,文件名字为" <<  fileInfo.baseName();
//                qDebug() << "Copied file:,修改时间为" << lastModified.toString("yyyyMMddhhmmss");
//                qDebug() << "Copied file:" << sourceFilePath;
//                WriteSaveInfo(serialnumber,fileInfo.baseName(),timestr,lastModified.toString("yyyyMMddhhmmss"),"");
//                // 删除源文件
//                if (!QFile::remove(sourceFilePath)) {
//                    qDebug() << "Failed to remove file:" << sourceFilePath;
//                    continue;
//                }
//                qDebug() << "Removed file:" << sourceFilePath;

//            }
//        }
//    }
//    return false;
//}
bool FileOperation::WriteSaveInfo(QString serialize,QString filename,QString time,QString filetime,QString Username, const QString& destinationDirPath)
{
    //QApplication::processEvents();
    QString ConfigName=QString("%1%2_%3.log").arg(destinationDirPath).arg(serialize).arg(time);
    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());
    // 打开配置文件
    QFile file(ConfigName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
    {
        qDebug() << "WriteSaveInfo 4 Failed to open file.";
        return false;
    }
    else if(Username=="")
    {
        QTextStream out(&file);
        QString str= QString("%1,%2,%3").arg(time).arg(filename).arg(filetime);
        out << str<<endl;
        // 关闭日志文件
        file.close();
        return true;
    }else
    {
        QTextStream out(&file);
        QString str= QString("%1_%2 %3 %4").arg(serialize).arg(time).arg(serialize).arg(Username);
        out << str<<endl;
        // 关闭日志文件
        file.close();
        return true;
    }
    return false;
}
QString FileOperation::validateFileName( QString fileName)
{
    // 定义正则表达式
    QRegularExpression regex("^(\\d+_?(\\d+)_?\\d+_?\\d+_\\d+_\\d+_\\[IMP\\].mp4)$");

    // 匹配正则表达式
    QRegularExpressionMatch match = regex.match(fileName);

    // 检查是否匹配
    if (match.hasMatch()) {
        // 获取捕获组的值，即警情编号
        return match.captured(1);
    } else {
        return QString();  // 如果未匹配，返回空字符串
    }
}

//写入保存文件
bool FileOperation::WriteSaveInfo(QString serialize,QString filename,QString time,QString filetime,QString Username,QString case_number, const QString& destinationDirPath)
{
    // QApplication::processEvents();
    QString ConfigName=QString("%1%2_%3.log").arg(destinationDirPath).arg(serialize).arg(time);
    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());
    // 打开配置文件
    QFile file(ConfigName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
    {
        qDebug() << "WriteSaveInfo 4 Failed to open file.";
        return false;
    }
    else if(Username=="")
    {
        QTextStream out(&file);
        QString str= QString("%1,%2,%3,,,%4").arg(time).arg(filename).arg(filetime).arg(case_number);
        out << str<<endl;
        // 关闭日志文件
        file.close();
        return true;
    }else
    {
        QTextStream out(&file);
        QString str= QString("%1_%2 %3 %4").arg(serialize).arg(time).arg(serialize).arg(Username);
        out << str<<endl;
        // 关闭日志文件
        file.close();
        return true;
    }
    return false;
}
//写入保存文件
bool FileOperation::WriteSaveInfo(QString serialize,QString filename,QString time,QString filetime,QString Username,QString case_number,QString trafficCaseTable,QString file_type_id, const QString& destinationDirPath)
{
    //QApplication::processEvents();
    QString ConfigName=QString("%1%2_%3.log").arg(destinationDirPath).arg(serialize).arg(time);
    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());
    // 打开配置文件
    QFile file(ConfigName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
    {
        qDebug() << "WriteSaveInfo 4 Failed to open file.";
        return false;
    }
    else if(Username=="")
    {
        QTextStream out(&file);
        QString str= QString("%1,%2,%3,,%4,%5,%6").arg(time).arg(filename).arg(filetime).arg(case_number).arg(trafficCaseTable).arg(file_type_id);
        out << str<<endl;
        // 关闭日志文件
        file.close();
        return true;
    }else
    {
        QTextStream out(&file);
        QString str= QString("%1_%2 %3 %4").arg(serialize).arg(time).arg(serialize).arg(Username);
        out << str<<endl;
        // 关闭日志文件
        file.close();
        return true;
    }
    return false;
}
//获取指定路径下所有.log文件,找到记录行数大于两行的文件名
void FileOperation::findLogFiles(const QString& path)
{
    QApplication::processEvents();
    QDir directory(path);
    QStringList files = directory.entryList(QStringList() << "*.log", QDir::Files);

    foreach(const QString& filename, files) {
        QFile file(directory.absoluteFilePath(filename));
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&file);
            int lineCount = 0;
            while (!in.atEnd()) {
                in.readLine();
                lineCount++;
            }
            if (lineCount > 2) {
                qDebug() << "File:" << filename;
            }
            file.close();
        }
    }
}

//查询指定路径下的所有文件的修改时间，修改时间再startDate到QDateTime范围的打印出他的文件名
void FileOperation::findFilesByCreationDate(const QString& path, const QString& startDate, const QString& endDate,const QString& OfficerID,const QString& productNumber)
{
    QApplication::processEvents();
    FileInfo finfo;
    QDir sourceDir(path);

    // 获取源目录中的所有文件和文件夹
    QStringList fileList = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

    // 遍历文件列表
    foreach (QString file, fileList) {
        QString sourceFilePath = sourceDir.filePath(file);


        QFileInfo fileInfo(sourceFilePath);
        QDateTime lastModified = fileInfo.lastModified();
        QString Datetime=lastModified.toString("yyyyMMddhhmmss");
        if(Datetime<=endDate&&Datetime>=startDate)//获取文件时间比较
        {
            // 如果是文件夹，则递归
            if(productNumber!=""&&!sourceFilePath.contains(productNumber))
            {
                continue;
            }
            else
            {
                //QString Datetime=lastModified.toString("yyyyMMddhhmmss");

                QString substring = sourceFilePath.mid(sourceFilePath.lastIndexOf("/") + 1);
                substring = substring.left(substring.indexOf("_"));

                finfo.fileName=fileInfo.baseName();
                finfo.sourceFilePath=sourceFilePath;
                finfo.officerID=OfficerID;
                finfo.lastModified=Datetime;
                finfo.productNumber=substring;
                filelist.push_back(finfo);
                qDebug() << "Copied file:,文件名字为" <<  fileInfo.baseName();
                qDebug() << "Copied file:" << sourceFilePath;
            }
        }
    }
}

//查询指定路径下的所有文件的修改时间，修改时间再startDate到QDateTime范围的打印出他的文件名
void FileOperation::findFilesByCreationDate(const QString& path)
{
    QApplication::processEvents();
    QDir sourceDir(path);

    // 获取源目录中的所有文件和文件夹
    QStringList fileList = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

    // 遍历文件列表
    foreach (QString file, fileList) {
        QString sourceFilePath = sourceDir.filePath(file);

        if (QFileInfo(sourceFilePath).isDir()) {
            findFilesByCreationDate(sourceFilePath);
        }else {
            // 如果是文件且是MP4或JPG格式，则拷贝到目标目录
            QFileInfo fileInfo(sourceFilePath);
            QString fileExtension = fileInfo.suffix().toLower();
            if (fileExtension == "mp4"|| fileExtension == "avi"||fileExtension ==  "mkv"|| fileExtension == "mov") {
                video.push_back(sourceFilePath);
                qDebug() << "Copied file:,文件名字为" <<  fileInfo.baseName();
                qDebug() << "Copied file:" << sourceFilePath;

            }
            if ( fileExtension == "jpg"||fileExtension == "gif") {
                picture.push_back(sourceFilePath);
                qDebug() << "Copied file:,文件名字为" <<  fileInfo.baseName();
                qDebug() << "Copied file:" << sourceFilePath;

            }
            if ( fileExtension == "log"||fileExtension == "text"||fileExtension == "txt") {
                log.push_back(sourceFilePath);
                qDebug() << "Copied file:,文件名字为" <<  fileInfo.baseName();
                qDebug() << "Copied file:" << sourceFilePath;

            }
            if ( fileExtension == "wav"||fileExtension == "mp3") {
                audio.push_back(sourceFilePath);
                qDebug() << "Copied file:,文件名字为" <<  fileInfo.baseName();
                qDebug() << "Copied file:" << sourceFilePath;

            }
        }
    }
}
//写入保存文件
bool FileOperation::WriteZFYConfig(QString Disk,QString DeviceID,QString MName,QString Model)
{
    QApplication::processEvents();
    QString ConfigName=QString("%1/ZFYConfig.ini").arg(Disk);
    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());
    // 打开配置文件
    QFile file(ConfigName);
    if (!file.open(QIODevice::ReadWrite | QIODevice::Append))
    {
        WriteInfo( "WriteSaveInfo 4 Failed to open file.");
        return false;
    }else
    {

        QTextStream out(&file);
        QString str= QString(";必须填写! 产品序列号,长度为7位数字，且在系统中是唯一的，不能重复；");
        out << str<<endl;
        str= QString("PID=%1").arg(DeviceID);
        out << str<<endl;
        str= QString(";厂商名称,字母");
        out << str<<endl;
        str= QString("VID=%1").arg(MName);
        out << str<<endl;
        str= QString(";产品型号");
        out << str<<endl;
        str= QString("PTYPE=%1").arg(Model);
        out << str<<endl;
        str= QString(";用户编号，长度为6，字母、数字、字母+数字");
        out << str<<endl;
        str= QString("USERID=%1").arg("");
        out << str<<endl;
        str= QString(";用户名称，字母");
        out << str<<endl;
        str= QString("USERNAME=%1").arg("");
        out << str<<endl;
        str= QString(";单位编号，最大长度12位数字");
        out << str<<endl;
        str= QString("UNITID=%1").arg("");
        out << str<<endl;
        str= QString(";单位名称");
        out << str<<endl;
        str= QString("UNITNAME=%1").arg("");
        out << str<<endl;
        // 关闭日志文件
        file.close();
        return true;
    }
    return false;
}
void FileOperation::GetTotalSizeOfFiles(const QString &directoryPath,double& totalSize)
{

    QDir sourceDir(directoryPath);
    // 获取源目录中的所有文件和文件夹
    QStringList fileList = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
    // 遍历文件列表
    foreach (QString file, fileList) {
        QString sourceFilePath = sourceDir.filePath(file);
        if (QFileInfo(sourceFilePath).isDir()) {
            WriteInfo(QString("GetTotalSizeOfFiles,sourceFilePath=%1").arg(sourceFilePath));
            GetTotalSizeOfFiles(sourceFilePath,totalSize);
        } else {
            // 如果是文件且是MP4或JPG格式，则拷贝到目标目录的相应子目录下
            QFileInfo fileInfo(sourceFilePath);
            QString fileExtension = fileInfo.suffix().toLower();

            if (fileExtension == "mp4"||fileExtension == "mov"||fileExtension == "mpg"||fileExtension == "avi"||fileExtension == "mts"||fileExtension == "flv"||fileExtension == "3gp"||fileExtension == "mkv") {
                QDateTime lastModified = fileInfo.lastModified();
                qint64 fileSize = fileInfo.size();  // 获取文件大小，以字节为单位
                totalSize +=fileSize/ (1024 * 1024);
                WriteInfo(QString("GetTotalSizeOfFiles,fileSize=%1").arg(fileSize));
            } else if (fileExtension == "jpg"||fileExtension == "jpeg"||fileExtension == "png"||fileExtension == "bmp") {
                QDateTime lastModified = fileInfo.lastModified();
                qint64 fileSize = fileInfo.size();  // 获取文件大小，以字节为单位
                totalSize +=fileSize/ (1024 * 1024);
                WriteInfo(QString("GetTotalSizeOfFiles,fileSize=%1").arg(fileSize));
            } else if (fileExtension == "txt"||fileExtension == "log") {
                QDateTime lastModified = fileInfo.lastModified();
                qint64 fileSize = fileInfo.size();  // 获取文件大小，以字节为单位
                totalSize +=fileSize/ (1024 * 1024);
                WriteInfo(QString("GetTotalSizeOfFiles,fileSize=%1").arg(fileSize));
            } else if (fileExtension == "wav"||fileExtension == "aac"||fileExtension == "mp3"||fileExtension == "3gpp") {
                QDateTime lastModified = fileInfo.lastModified();
                qint64 fileSize = fileInfo.size();  // 获取文件大小，以字节为单位
                totalSize +=fileSize/ (1024 * 1024);
                WriteInfo(QString("GetTotalSizeOfFiles,fileSize=%1").arg(fileSize));
            } else {
                // 如果是其他文件类型，则不进行拷贝
                continue;
            }
        }
    }

    return;
}
//查询指定路径下的所有log文件
void FileOperation::findFileLog(const QString& path)
{
    QApplication::processEvents();
    QDir sourceDir(path);

    // 获取源目录中的所有文件和文件夹
    QStringList fileList = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

    // 遍历文件列表
    foreach (QString file, fileList) {
        QString sourceFilePath = sourceDir.filePath(file);

        if (QFileInfo(sourceFilePath).isDir()) {
            break;
        }else {
            // 如果是文件且是MP4或JPG格式，则拷贝到目标目录
            QFileInfo fileInfo(sourceFilePath);
            QString fileExtension = fileInfo.suffix().toLower();
            if ( fileExtension == "log"||fileExtension == "text"||fileExtension == "txt") {
                log.push_back(sourceFilePath);
                qDebug() << "Copied file:,文件名字为" <<  fileInfo.baseName();
                QString name=fileInfo.baseName();
                qDebug() << "Copied file:" << sourceFilePath;
                int colonIndex = name.indexOf("_"); // 查找冒号的索引位置
                QString leftname=name.left(colonIndex);

                // Open the file
                QFile file(sourceFilePath);
                if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                    // Read the first line
                    QTextStream in(&file);
                    QString firstLine = in.readLine();

                    // Process or print the first line as needed
                    qDebug() << "First line:" << firstLine;

                    // Close the file when done
                    file.close();
                }
            }

        }
    }
}
qint64 FileOperation::getFolderSize(const QString& folderPath)
{
    QDir directory(folderPath);

    if (!directory.exists()) {
        qDebug() << "Folder does not exist!";
        return -1; // 或者根据需求返回其他值
    }

    qint64 totalSize = 0;

    QStringList fileList = directory.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
    foreach (const QString &file, fileList) {
        QString filePath = folderPath + QDir::separator() + file;
        QFileInfo fileInfo(filePath);

        if (fileInfo.isDir()) {
            // 递归获取子文件夹的大小
            qint64 subfolderSize = getFolderSize(filePath);
            if (subfolderSize == -1) {
                return -1; // 递归获取失败，返回错误
            }
            totalSize += subfolderSize;
        } else if (fileInfo.isFile()) {
            totalSize += fileInfo.size();
        }
    }

    return totalSize;
}
//根据key读取路径配置文件
bool FileOperation::ReadVerInfo(QString ConfigName,QString key,QString &value)
{
    qDebug() << "ReadVerInfo";
    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());
    // 打开配置文件
    QFile file(ConfigName);
    try {
        if (!file.open(QIODevice::ReadOnly  | QIODevice::Text))
        {
            qDebug() << "Failed to open file.";
            return false;
        }
        QTextStream reader(&file);
        // 设置文件编码为UTF-8
        reader.setCodec("UTF-8");
        // 遍历配置文件
        while (!reader.atEnd())
        {
            QString str =reader.readLine();
            QStringList parts = str.split(':');

            if (parts.size() >= 2) {
                QString key1 = parts[0];
                QString value1 = parts[1];
                QString utf8Value = value1.toUtf8();
                qDebug() <<key1<<key;
                if(key==key1.toUtf8()&&value1!="")
                {
                    value=utf8Value;
                    qDebug() << "Key: " << key;
                    qDebug() << "Value: " << utf8Value;
                    // 关闭配置文件
                    file.close();
                    return true;
                }
            }
        }
        // 关闭配置文件
        file.close();
        return false;
    } catch (const std::exception& e) {

        file.close(); // Ensure the file is closed even in case of an exception.
        return false;
    }
}
QString FileOperation::extractTimestamp(const QString &filename) {
    // 正则表达式匹配yyyyMMddHHmmss格式的时间戳
    // 假设时间戳后面紧跟着非数字字符（如下划线、点等）
    QRegularExpression regex(R"(\d{4}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])(0[0-9]|1\d|2[0-3])([0-5]\d){2})");
    QRegularExpressionMatch match = regex.match(filename);

    if (match.hasMatch()) {
        // 提取整个匹配项，即时间戳
        return match.captured(0);
    }

    // 如果没有匹配项，返回空字符串
    return QString();
}
